package com.jiaozi.core.security.service;

import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateUtil;
import com.jiaozi.base.redis.RedisEnum;
import com.jiaozi.base.redis.RedisUtil;
import com.jiaozi.base.utils.bean.enums.REnum;
import com.jiaozi.core.exception.CommonException;
import com.jiaozi.system.enums.ConfigsEnum;
import com.jiaozi.system.service.SysConfigsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 登录账号错误登录限制
 */
@Slf4j
@Service
public class LoginLockServiceImpl {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysConfigsService sysConfigsService;
    /**
     * 判断当前是否锁定
     * @param userName
     */
    public void isLock(String userName){
        //判断账户是否锁定
        if(redisUtil.existsKey(RedisEnum.LOGIN_ERROR_ACCOUNT_LOCK,userName)){
            Long l=redisUtil.ttl(RedisEnum.LOGIN_ERROR_ACCOUNT_LOCK,userName);
            throw new CommonException(REnum.LOGIN_ACCOUNT_LOCK,"账户已锁定,"+DateUtil.formatBetween(l*1000, BetweenFormatter.Level.SECOND)+"后解除");
        }

    }

    /**
     * 登录失败
     */
    public void loginError(String userName){
        //判断账户是否存在错误
        if(!redisUtil.existsKey(RedisEnum.LOGIN_ERROR_ACCOUNT_NUM,userName)){
            redisUtil.setStringExpire(RedisEnum.LOGIN_ERROR_ACCOUNT_NUM,userName,"0", Long.valueOf(sysConfigsService.getSysConfigs(ConfigsEnum.LOGIN_PASSWORD_ERROR_LOCKED_TIME) ));
        }
        //增加错误次数
        redisUtil.incrStorage(RedisEnum.LOGIN_ERROR_ACCOUNT_NUM,userName,"1");
        //判断是否到达错误上限
        if(Integer.valueOf(redisUtil.getString(RedisEnum.LOGIN_ERROR_ACCOUNT_NUM,userName))>=Long.valueOf(sysConfigsService.getSysConfigs(ConfigsEnum.LOGIN_PASSWORD_ERROR_NUM) ).intValue()){
            redisUtil.setStringExpire(RedisEnum.LOGIN_ERROR_ACCOUNT_LOCK,userName,"1",Long.valueOf(sysConfigsService.getSysConfigs(ConfigsEnum.LOGIN_PASSWORD_ERROR_LOCKED_TIME )));
        }


    }

    /**
     * 登录成功
     */
    public void loginSeccess(String userName){
        redisUtil.removeString(RedisEnum.LOGIN_ERROR_ACCOUNT_LOCK,userName);
        redisUtil.removeString(RedisEnum.LOGIN_ERROR_ACCOUNT_NUM,userName);
     }




}
